<!-- SideBarItem.vue -->
<template>
  <!-- 外链 -->
  <a v-if="isExternal" :href="item.path" target="_blank" rel="noopener" class="external-link">
    <el-menu-item :index="item.path">
      <el-icon :size="18" v-if="item.meta?.icon">
        <component :is="item.meta.icon" />
      </el-icon>
      <span slot="title">{{ item.meta?.title || item.name }}</span>
    </el-menu-item>
  </a>

  <!-- 叶子节点 -->
  <el-menu-item
    v-else-if="!item.children?.length"
    :index="resolvePath(item.path)"
  >
    <el-icon :size="18" v-if="item.meta?.icon">
      <component :is="item.meta.icon" />
    </el-icon>
    <span slot="title">{{ item.meta?.title || item.name }}</span>
  </el-menu-item>

  <!-- 含子级 -->
  <el-menu-item v-else :index="resolvePath(item.path)">
    <template slot="title">
      <el-icon :size="18" v-if="item.meta?.icon">
        <component :is="item.meta.icon" />
      </el-icon>
      <span slot="title">{{ item.meta?.title || item.name }}</span>
    </template>

    <side-bar-item
      v-for="child in item.children"
      :key="child.path"
      :item="child"
      :base-path="resolvePath(item.path)"
    />
  </el-menu-item>
</template>

<script>

export default {
  name: 'SideBarItem',
  props: {
    item: { type: Object, required: true },
    basePath: { type: String, default: '' }
  },
  computed: {
    isExternal() {
      return /^(https?|mailto|tel):/.test(this.item.path)
    }
  },
  methods: {
    pathResolve(basePath, routePath) {
        if (routePath.startsWith('/')) return routePath                 // 绝对路径
        return basePath.replace(/\/+$/, '') + '/' + routePath.replace(/^\/+/, '')
    },
    resolvePath(routePath) {
        if (this.isExternal) return routePath
        return this.pathResolve(this.basePath, routePath)
    }
  }
}
</script>

<style scoped>
.external-link {
  text-decoration: none;
  color: inherit;
}
</style>